
import {
    toast,
    promptBox,
    print,
    output
} from 'nc-lightapp-front';

import CommonAction from '../../../actions/common';

import FormEditAction from './formEdit';
import {saveValidate, getAppPageConfig} from '../../../../../../hrpub/common/utils/utils';

export default class Main extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
    }

    extend = [FormEditAction]

    clickHandle = {}

    didAllInstance = () => {
        this.setEventHandle();
    }

    // 提交单据
    submitBills = async (selectedRows) => {
        const {action} = this.comp;

        await action.rowAct.submitOnes(selectedRows);
        action.formAct.toBrowsePage(selectedRows);
    }

    // 收回单据
    callbackBill = async (selectedRows) => {
        const {action} = this.comp;
        await action.rowAct.callbackOnes(selectedRows);
        action.formAct.toBrowsePage(selectedRows);
    }

    // 设置点击事件map
    setEventHandle = () => {
        const {action} = this.comp;

        this.clickHandle = {
            'save': this.saveAddPage,
            'browse_status': {
                'edit': this.toAddPageEditStatus,
                'commit': this.submitBills,
                'recover': this.callbackBill,
                'del': this.deleteBill,
                'copy': action.rowAct.copyOnes,
                'print': this.print,
                'out': this.output,
                'CheckBudget': action.orgSta.openOrgSituationModal,
                'cardrpt': this.jointSearch,
                'viewctrt': action.vcAct.showViewContactModal,
                'check_appr_opini': action.rowAct.previewApproveInfo,
                'sendMsg': this.sendMessage,
                'add': action.formAct.toAddPage,
                'refresh': action.formAct.toBrowsePage,
                'execute': action.rowAct.openExecModal,
                'file': this.comp.props.fileManager
            }
        };
    }

    // 发送通知
    sendMessage = (selectedRows) => {
        this.pubSub.publish('sendMessage', selectedRows);
    }

    // 卡片删除按钮
    deleteBill = (selectedRows) => {
        const {action} = this.comp;

        action.rowAct.deleteRows(selectedRows)
            .then((res) => {
                if(res) {
                    this.goToBackMainPage();
                }
            });
    }

    // 新增页面头部按钮点击处理
    addHeaderClick = (btnCode) => {
        console.log(btnCode);
        const {props} = this.comp;
        const {form} = props;
        return (props, bCode) => {
            console.log(bCode);
            let selectedRows = [{
                ...form.getAllFormValue('card').rows[0]
            }];
            // 新增页面保存按钮
            if(typeof this.clickHandle[btnCode] === 'function') {
                this.clickHandle[btnCode](selectedRows);
            }
            else if(typeof this.clickHandle[btnCode][bCode] === 'function') {
                this.clickHandle[btnCode][bCode](selectedRows)
            }
        }
    }

    // 从浏览态变成编辑态
    toAddPageEditStatus = (selectedRows) => {
        this.comp.action.rowAct.editOnes(selectedRows);
    }

    // 新增页面保存
    saveAddPage = async () => {
        const {props, action} = this.comp;
        const {dispatch, form, emp} = props;

        await saveValidate(
            props,
            '60092090nccloud',
            'card',
            [],
            'form',
            null,
            null
        );


        if(form.isCheckNow('card')) {
            let postData = {
                formData: form.getAllFormValue('card'),
                pk_org: emp.orgValue.refpk
            };
            try {
                    let res = await dispatch({
                        type: 'emp/addPageSave',
                        payload: {
                            postData: postData
                        }
                    });

                    if(res.success) {
                        toast({
                            color: 'success',
                            content: emp.language['gx6008-000030'] // 保存成功
                        });
                        action.formAct.toBrowseStatus(res.data.formData.card);
                    }
                }
            catch(e) {
            }
        }
    }

    didMount = () => {
        const {props} = this.comp;
        const {form, meta, emp} = props;

        form.setFormItemsDisabled('card', {
            pk_org: form.getFormItemsDisabled('card', 'pk_org')
        });
    }

    // 返回按钮返回主页面表格
    goToBackMainPage = () => {
        const {props} = this.comp;
        const {dispatch, button, emp} = props;

        dispatch({
            type: 'emp/update',
            payload: {
                page: 'main'
            }
        });

        button.setButtonVisible({
            add: true,
            edit: false,
            del: true,
            search: true,
            commit: true,
            print: true,
            batchAdd: true,
            recover: true,
            approveinfo: true,
            refresh: true,
            save: false,
            cancel: false,
            first: false,
            pre: false,
            next: false,
            last: false,
            copy: false,
            aux_func: true,
            cardrpt: false,
            check_appr_opini: false,
            sendMsg: true,
            execute: true,
            file: false
        });
        button.setButtonVisible({
            save: false,
            cancel: false
        });

        if(emp.page === 'add') {
            this.cancelPost();
        }

        this.pubSub.publish('getMainTableData');
    }

    // 取消编辑
    cancelFormEdit = () => {
        const {props, action} = this.comp;
        const {emp, dispatch, form, meta, button} = props;

        promptBox({
            color: 'info',
            title: emp.language['gx6008-000036'], // '确认取消',
            content: emp.language['gx6008-000037'], // '是否确认取消
            beSureBtnClick: () => {
                let formValue = form.getAllFormValue('card');
                let billId = formValue.rows[0].values['pk_partmng'].value;

                
                if(emp.page === 'add') {
                    this.cancelPost();
                }
                if(emp.page === 'add' || !billId) {
                    this.goToBackMainPage();
                }
                else {
                    const template = meta.getMeta();
                    template['formrelation']['card'].map((item) => {
                        form.cancel(item);
                    });
                    action.formAct.toBrowseStatus();
                    this.showHistoryData();
                }
            }
        });
    }

    // 根据存储的数据展示编辑前
    showHistoryData = () => {
        const {props} = this.comp;
        const {emp, dispatch, form} = props;

        if(emp.addPageHistoryData) {
            form.setAllFormValue({
                card: emp.addPageHistoryData
            });
            this.update({
                addPageHistoryData: null 
            });
        }
    }

    // 新增取消需要请求一个接口
    cancelPost = () => {
        const {props, action} = this.comp;
        const {emp, dispatch, form, meta, button} = props;

        let postData = {
            formData: form.getAllFormValue('card'),
            pk_org: emp.orgValue.refpk
        };

        return dispatch({
            type: 'emp/cancelAdd',
            payload: {
                postData: postData
            }
        });
    }

    // 打印
    print = () => {
        let formValue = this.comp.props.form.getAllFormValue('card');

        print('pdf', '/nccloud/hrtrn/partapply/PartPrintAction.do', {
            appcode: '60092090',
            nodekey: '60092090',
            oids: [formValue.rows[0].values['pk_partmng'].value]
        });
    }

    // 输出
    output = () => {
        let formValue = this.comp.props.form.getAllFormValue('card');

        output({
            url: '/nccloud/hrtrn/partapply/PartPrintAction.do',
            data: {
                appcode: '60092090',
                nodekey: '60092090',
                oids: [formValue.rows[0].values['pk_partmng'].value],
                outputType: 'output',
                filename: this.comp.props.emp.language['gx6008-000247']
            },
            callback: () => {
            }
        });
    }

    // 联查人员卡片
    jointSearch = async () => {
        const {props, action} = this.comp;
        const {form, btnAct} = props;
        
        let formData = form.getAllFormValue('card');
        
        btnAct.wpsview.openView(formData.rows);
    }
}